import { instantiate, Node, Prefab } from "cc";
import { ResMgr } from "../../frame/mgr/ResMgr";
import { ViewMgr } from "../../frame/mgr/ViewMgr";
import { IView, IViewDataProccesor, TViewConfig } from "./IView";
import { ViewComponent } from "./ViewComponent";


export abstract class ViewCtrlBase {

    model: any = null;
    node: Node = null;

    constructor(
        public resMgr: ResMgr,
        public viewMgr: ViewMgr,
        public dep: any[],
        public config: TViewConfig
    ) {
        this.parseDep();
    }

    get dataProccesor(): IViewDataProccesor {
        return this.viewMgr.data.dataProccesorMap.get(this.config.id);
    }

    onShow(): void {
        const { id, bundle, prefab, atlasArr } = this.config;
        this.resMgr.loadBundle(id, bundle).then(() => {
            this.resMgr.loadAtlasArrByBundle(id, bundle, atlasArr).then(() => {
                this.resMgr.loadPrefab(id, bundle, prefab).then((prefabAsset: Prefab) => {
                    this.createView(prefabAsset);
                    this.view.dep = this;
                    this.refreshUI();
                })
            })
        })
    }

    onHide(): void {
        this.removeView();
    }

    createView(prefabAsset: Prefab): void {
        const { name, layer } = this.config;
        const node = instantiate(prefabAsset);
        node.name = name;
        this.viewMgr.addNodeToLayer(layer, node);
        this.node = node;
    }

    removeView(): void {
        const { layer } = this.config;
        this.viewMgr.removeNodeFromLayer(layer, this.node);
        this.node = null;
    }

    close(): void {
        const { id } = this.config;
        this.viewMgr.close(id)
    }

    abstract parseDep(): void;

    abstract get view(): any;

    abstract refreshUI(): void

    abstract dispose(): void;
}

